package com.k2data.k2de.utils;

import k2platform.common.util.AssetServiceUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class CheckAssetsUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(CheckAssetsUtil.class);

    //设备 set
    private static Set<String> assets;

    /**
     * 获取所有asset compoundIdStr集合
     */
    public static void getAllAssets(String sdmApiUrl) {
        List<Map<String, String>> compoundIdList = AssetServiceUtils.getAllAsset(sdmApiUrl, null);

        assets = new HashSet<>();
        if (compoundIdList == null) {
            LOGGER.error("Request sdm api: query assets error.");
            System.exit(-1);
        }

        for (Map<String, String> compoundId : compoundIdList) {
            String compoundIdStr = getStrPresentationByCompoundId(compoundId);
            assets.add(compoundIdStr);
        }

        LOGGER.info("Cache all Assets success...");
    }

    /**
     * 判断compoundIdStr是否存在,不存在新建asset
     */
    public static boolean checkAndAddAssetWhenItIsNonExistent(String fieldGroupId, Map<String, String> compoundId,
                                                              String sdmApiUrl, String compoundIdDescription) {
        LOGGER.info("Check asset start...");

        String compoundIdStr = getStrPresentationByCompoundId(compoundId);
        //check if exist
        if (assets.contains(compoundIdStr)) {
            return true;
        }

        LOGGER.info("CompoundId({}) is non-existent and will be registered.");

        // Add new asset
        String assetName = fieldGroupId + "_" + (assets.size() + 1);
        int res = AssetServiceUtils.addAsset(sdmApiUrl, fieldGroupId, assetName, compoundId, compoundIdDescription);
        //201表示创建成功 ,409表示已存在.
        if (res == 201 || res == 409) {
            //save new asset
            LOGGER.debug("CompoundId  register success.");
            assets.add(compoundIdStr);
            return true;
        } else {
            LOGGER.warn("CompoundId register fail, responseCode:{}", res);
            return false;
        }
    }

    /**
     * 通过compoundId获取它的字符串表示形式.
     *
     * @param compoundId
     * @return
     */
    private static String getStrPresentationByCompoundId(Map<String, String> compoundId) {
        StringBuilder sb = new StringBuilder("");
        for (String str : compoundId.keySet()) {
            sb.append(compoundId.get(str)).append("_");
        }
        return sb.substring(0, sb.lastIndexOf("_"));
    }
}
